<style lang="scss" scoped>
  .status-0, .status-2{ color: #ee0a24; }
  .status-1{ color: #ff976a; }
  .status-3{ color: #07c160; }
  .infos-box{
    .avatar-upload{
      width: 100%;
      display: flex;
      align-items: center;
      justify-content: center;
    }
    .avatar{
      width: 2.44rem;
      height: 2.44rem;
      background-color: #fff;
      border-radius: 50%;
      margin: .2rem auto;
      position: relative;
      > img{
        width: 100%;
        height: 100%;
        border-radius: 50%;
      }
      .edit{
        position: absolute;
        right: 0;
        top: .4rem;
        width: 30px;
        height: 30px;
        border-radius: 50%;
        background-color: #fff;
        display: flex;
        align-items: center;
        justify-content: center;
      }
    }
    .cells{

    }
    .tips{
      margin: .2rem .6rem;
      font-size: .24rem;
      color: #666;
      line-height: 1.5;
    }
    .submit{
      margin: .2rem;
    }
  }

  .modal-box{
    padding: .2rem .4rem;
    input,textarea{
      padding: .2rem;
      outline: none;
      border: 1px solid #e9e9e9;
      background-color: #fff;
      border-radius: 4px;
      width: 100%;
      min-height: .64rem;
    }
  }
</style>

<template>
  <div class="container hasNav">
    <van-nav-bar
        title="个人资料"
        left-arrow
        left-text="返回"
        @click-left="$router.back()"
        fixed />

    <div class="infos-box">
      <div class="avatar-upload">
        <van-uploader
            :after-read="afterAvatarRead"
            :max-size="5 * 1024 * 1024"
        >
          <div class="avatar">
            <img :src="fileUrl + form.avatar" v-if="form.avatar">
            <div class="edit">
              <van-icon name="edit" color="#179AFE" size="24" />
            </div>
          </div>
        </van-uploader>
      </div>
      <div class="cells">
        <van-cell
            title="我能陪诊"
            to="/user/certAuth?type=1"
            is-link >
          <div :class="`status-${userInfo.authstatus}`">{{getAuthStatusName(userInfo.authstatus)}}</div>
        </van-cell>
        <van-cell
            title="我能陪护"
            to="/user/certAuth?type=2"
            is-link >
          <div :class="`status-${userInfo.chaperonageAuthStatus}`">{{getAuthStatusName(userInfo.chaperonageAuthStatus)}}</div>
        </van-cell>
        <van-cell
            title="姓名"
            :value="form.name"
            @click="showModalEvent(0)"
            :is-link="!isAuthed" />
        <van-cell
            title="性别"
            :value="genderName"
            @click="showGenderEvent"
            :is-link="!isAuthed" />
        <van-cell
            title="出生日期"
            :value="`${!!form.birth ? $moment(form.birth).format('YYYY年MM月DD日') : '未填写'}`"
            @click="showBirthEvent"
            :is-link="!isAuthed" />
        <van-cell
            title="擅长"
            :value="form.skill"
            @click="showModalEvent(1)"
            is-link />
        <van-cell
            title="兴趣爱好"
            :value="form.hobby"
            @click="showModalEvent(2)"
            is-link />
      </div>

      <div class="tips">
        请完善您的基本信息，申请您能提供的服务认证，系统将于3个工作日内审核处理.
      </div>

      <div class="submit">
        <van-button block type="default" color="#179AFE" @click="onSubmit">保存</van-button>
      </div>
    </div>

    <!-- 填写姓名、擅长、兴趣爱好 -->
    <van-dialog
        v-model="showModal"
        :title="`请填写${modalTitle}`"
        @confirm="handleModalConfirm"
        @open="handleModalOpen"
        @close="handleModalClose"
        show-cancel-button>
      <div class="modal-box">
        <template v-if="modalType === 0">
          <input type="text" v-model="modalValue" maxlength="20" placeholder="请填写姓名">
        </template>
        <template v-if="modalType === 1">
          <textarea v-model="modalValue" cols="30" rows="10" maxlength="1000" placeholder="请填写擅长，最多1000字。"></textarea>
        </template>
        <template v-if="modalType === 2">
          <textarea v-model="modalValue" cols="30" rows="10" maxlength="1000" placeholder="请填写兴趣爱好，最多1000字。"></textarea>
        </template>
      </div>
    </van-dialog>
    <!-- 选择性别 -->
    <van-action-sheet
        v-model="showGender"
        :actions="genders"
        cancel-text="取消"
        close-on-click-action
        @select="onGenderSelect" />

    <!-- 选择出生年月日 -->
    <van-popup v-model="showBirth" position="bottom">
      <van-datetime-picker
          type="date"
          :min-date="minDate"
          :max-date="maxDate"
          @confirm="onBirthConfirm"
          @cancel="showBirth = false"
          v-model="currentDate"
          :formatter="dateFormat"
      />
    </van-popup>
  </div>
</template>

<script>
  function isNull(val) {
    return val === '' || !val
  }
  import { mapGetters } from 'vuex'
  import { fileUrl } from '../../api/index';

  import {
    saveAvatar,
    saveInfos
  } from "../../api/user";

  export default {
    name: 'Infos',
    data() {
      return {
        fileUrl,
        showModal: false,
        showGender: false,
        showBirth: false,
        genders: [
          { name: '男', value: 1 },
          { name: '女', value: 2 }
        ],
        modalType: 0, // 0 姓名 1 擅长 2 兴趣爱好
        currentDate: new Date(),
        minDate: new Date(1970, 0, 1),
        maxDate: new Date(2050, 0, 1),
        form: {
          avatar: null,
          name: null,
          gender: 1,
          birth: null,
          skill: null,
          hobby: null
        },
        genderName: '',
        modalValue: ''
      };
    },
    mounted() {
      this.getDetail();
    },
    computed: {
      ...mapGetters(['userInfo']),
      modalTitle() {
        return this.modalType === 1 ? '擅长' : this.modalType === 2 ? '兴趣爱好' : '姓名'
      },
      isAuthed() {
        return this.userInfo.authstatus === 3 || this.userInfo.chaperonageAuthStatus === 3
      }
    },
    methods: {
      getDetail() {
        this.form.avatar = this.userInfo.headpic
        this.form.name = !isNull(this.userInfo.name) ? this.userInfo.name : '未填写'
        this.form.gender = +this.userInfo.gender
        this.form.genderName = this.genderName = +this.userInfo.gender === 1 ? '男' : +this.userInfo.gender === 2 ? '女' : '未填写'

        this.form.birth = !isNull(this.userInfo.birthday) ? this.userInfo.birthday : ''
        this.form.skill = !isNull(this.userInfo.introduction) ? this.userInfo.introduction : '未填写'
        this.form.hobby = !isNull(this.userInfo.interest) ? this.userInfo.interest : '未填写'
      },
      showModalEvent(index) {
        if(this.isAuthed && index === 0) {
          return this.$toast('您已通过认证，若要修改姓名、性别、生日，请联系系统助手!')
        }
        this.showModal = true;
        this.modalType = index;
      },
      showGenderEvent() {
        if(this.isAuthed) return this.$toast('您已通过认证，若要修改姓名、性别、生日，请联系系统助手!');
        this.showGender = true;
      },
      showBirthEvent() {
        if(this.isAuthed) return this.$toast('您已通过认证，若要修改姓名、性别、生日，请联系系统助手!');
        this.showBirth = true;
      },
      onGenderSelect(item) {
        this.form.gender = item.value;
        this.form.genderName = item.name
        this.genderName = item.name
      },
      onBirthConfirm(date) {
        this.showBirth = false;
        this.form.birth = this.$moment(date).format('YYYY-MM-DD')
      },
      dateFormat(type, val) {
        if (type === 'year') {
          return val + '年';
        }
        if (type === 'month') {
          return val + '月';
        }
        if (type === 'day') {
          return val + '日';
        }
        return val;
      },
      async afterAvatarRead(file) {
        let formData = new FormData();
        formData.append('headpic', file.file)

        const { headpic } = await saveAvatar(formData)
        this.form.avatar = headpic
        let userInfo = JSON.parse(JSON.stringify(this.userInfo))
        userInfo.headpic = headpic
        this.$store.commit('setUserInfo', userInfo)
        this.$toast('修改头像成功!')
      },
      handleModalConfirm() {
        let keyName = ['name', 'skill', 'hobby']
        if(isNull(this.modalValue)) {
          this.$toast('内容不能为空')
          return
        }
        this.form[keyName[this.modalType]] = this.modalValue;
      },
      handleModalOpen() {
        let keyName = ['name', 'skill', 'hobby']
        this.modalValue = this.form[keyName[this.modalType]]
      },
      handleModalClose() {
        this.modalValue = '';
      },
      async onSubmit() {
        let formData = new FormData();
        if(isNull(this.form.name)
          || isNull(this.form.gender)
          || isNull(this.form.birth)) {
          this.$toast('必须填写姓名、性别和生日')
          return
        }

        formData.append('name', this.form.name);
        formData.append('gender', this.form.gender);
        formData.append('birthdaytime', new Date(this.form.birth).getTime());
        formData.append('intro', this.form.skill);
        formData.append('interest', this.form.hobby);

        const { errorcode, errormsg } = await saveInfos(formData)

        if(!errorcode) {
          let userInfo = JSON.parse(JSON.stringify(this.userInfo))
          userInfo.name = this.form.name
          userInfo.gender = this.form.gender
          userInfo.birthday = this.form.birth
          userInfo.introduction = this.form.skill
          userInfo.interest = this.form.hobby

          this.$store.commit('setUserInfo', userInfo)
          this.$toast('保存成功')
        } else {
          this.$toast(errormsg)
        }
      },
      getAuthStatusName(status) {
        return status === 1 ? '认证中' :
          status === 2 ? '认证失败' :
            status === 3 ? '认证成功' : '未认证'
      }
    }
  };
</script>
